package org.blogwu.learn.multithread.chapter3.demo8;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class CyclicBarrierThread extends Thread {
    private CyclicBarrier cyclicBarrier;

    int ic;

    public CyclicBarrierThread(String name, CyclicBarrier cyclicBarrier, int ic) {
        super(name);
        this.cyclicBarrier = cyclicBarrier;
        this.ic = ic;
    }

    @Override
    public void run() {
        try {
            System.out.println(getName() + " 集结到位");
            cyclicBarrier.await();
            System.out.println(getName() + " 开始准备");
            Thread.sleep(2000);
            if (ic == 6) {
                throw new BrokenBarrierException();
            }
            System.out.println(getName() + " 准备完毕");
            cyclicBarrier.await();

        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (BrokenBarrierException e) {
            e.printStackTrace();
            cyclicBarrier.reset();//此方法会重置cyclicBarrier,并让等待中的线程抛出异常
            //将屏障重置为其初始状态。 如果任何一方当前正在屏障等待，他们将返回BrokenBarrierException。
        }
    }

    public static void main(String[] args) {
        Thread[] ts = new Thread[10];
        CyclicBarrier cyclicBarrier = new CyclicBarrier(10, new AccThread());
        for (int i = 0; i < 10; i++) {
            ts[i] = new CyclicBarrierThread("线" + i, cyclicBarrier, i);
            ts[i].start();
//            if (i==5){
//                ts[i].interrupt();
//            }
        }
    }
}

class AccThread extends Thread {

    boolean res = false;

    @Override
    public void run() {
        if (res) {
            System.out.println("准备完毕");
        } else {
            System.out.println("集结完毕");
            res = true;
        }
    }
}